<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { SelectOption } from 'naive-ui';
import { $t } from '@/locales';
import { type XxlJobLogSearchParams, fetchJobsByGroup, fetchXxlJobGroupOptions } from '@/service/api';

defineOptions({
  name: 'JobLogSearch'
});

interface Props {
  jobGroup: number;
  jobId: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'reset'): void;
  (e: 'search'): void;
}

const emit = defineEmits<Emits>();

const model = defineModel<XxlJobLogSearchParams>('model', { required: true });

function reset() {
  emit('reset');
}

function search() {
  emit('search');
}
const jobGroupOptions = ref<CommonType.Option<number>[]>([]);
async function getJobGroupOptions() {
  // 获取后台数据之前先设置一个默认值，防止界面刷新时显示滞后
  jobGroupOptions.value.unshift({
    label: $t('page.base.xxl.log.all'),
    value: 0
  });
  const { error, data } = await fetchXxlJobGroupOptions();

  if (!error) {
    const options = data.map(item => ({
      label: item.label,
      value: item.value
    }));
    jobGroupOptions.value = [...options];
    jobGroupOptions.value.unshift({
      label: $t('page.base.xxl.log.all'),
      value: 0
    });
    if (props.jobGroup > 0) {
      model.value.jobGroup = props.jobGroup;
      handleJobGroupUpdateValue(props.jobGroup.toString(), {});
    }
  }
}

// getJobGroupOptions();

const handleStatusOptions = [
  {
    label: $t('page.base.xxl.log.all'),
    value: -1
  },
  {
    label: $t('page.base.xxl.log.success'),
    value: 1
  },
  {
    label: $t('page.base.xxl.log.fail'),
    value: 2
  },
  {
    label: $t('page.base.xxl.log.running'),
    value: 3
  }
];

const jobSelectLoading = ref(false);

const jobOptions = ref<SelectOption[]>([]);
const tmpJobOptions = ref<SelectOption[]>([]);

const initJobOptions = () => {
  jobOptions.value.unshift({
    label: $t('page.base.xxl.log.all'),
    value: 0
  });
};

// initJobOptions();

const handleJobSearch = (query: string) => {
  if (!query.length) {
    jobOptions.value = tmpJobOptions.value;
    return;
  }
  jobSelectLoading.value = true;
  window.setTimeout(() => {
    jobOptions.value = tmpJobOptions.value.filter(item => (item.label as string).includes(query));
    jobSelectLoading.value = false;
  }, 10);
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function handleJobGroupUpdateValue(value: string, option: SelectOption) {
  if (Number.parseInt(value, 10) === 0) {
    jobOptions.value = [];
    initJobOptions();
    return;
  }

  const { data } = await fetchJobsByGroup(value);
  if (data !== null) {
    jobOptions.value = [];
    initJobOptions();
    data.map(item =>
      jobOptions.value.push({
        label: item.jobDesc,
        value: item.id
      })
    );
    tmpJobOptions.value = jobOptions.value;
    if (props.jobId > 0) {
      model.value.jobId = props.jobId;
      search();
    }
  }
}

onMounted(() => {
  getJobGroupOptions();
  initJobOptions();
});
</script>

<template>
  <NCard :title="$t('common.search')" :bordered="false" size="small" class="card-wrapper">
    <NForm :model="model" label-placement="left" :label-width="100">
      <NGrid responsive="screen" item-responsive>
        <NFormItemGi span="24 s:12 m:4" :label="$t('page.base.xxl.log.jobGroup')" path="jobGroup" class="pr-24px">
          <NSelect
            v-model:value="model.jobGroup"
            clearable
            :placeholder="$t('page.base.xxl.log.form.jobGroup')"
            :options="jobGroupOptions"
            @update:value="handleJobGroupUpdateValue"
          />
        </NFormItemGi>
        <NFormItemGi span="24 s:6 m:4" :label="$t('page.base.xxl.log.job')" path="jobId" class="pr-24px">
          <NSelect
            v-model:value="model.jobId"
            clearable
            :loading="jobSelectLoading"
            remote
            filterable
            :placeholder="$t('page.base.xxl.log.form.job')"
            :options="jobOptions"
            @search="handleJobSearch"
          />
        </NFormItemGi>
        <NFormItemGi span="24 s:6 m:4" :label="$t('page.base.xxl.log.jobStatus')" path="logStatus" class="pr-24px">
          <NSelect
            v-model:value="model.logStatus"
            clearable
            :placeholder="$t('page.base.xxl.log.form.jobStatus')"
            :options="handleStatusOptions"
          />
        </NFormItemGi>
        <NFormItemGi span="24 s:12 m:6" :label="$t('page.base.xxl.log.triggerTime')" path="filterTime" class="pr-24px">
          <DataPicker v-model:value="model.filterTime" type="datetimerange" :is-picker-options="true" />
        </NFormItemGi>
        <NFormItemGi span="24 s:12 m:3">
          <NSpace class="w-full" justify="end">
            <NButton @click="reset">
              <template #icon>
                <icon-ic-round-refresh class="text-icon" />
              </template>
              {{ $t('common.reset') }}
            </NButton>
            <NButton type="primary" ghost @click="search">
              <template #icon>
                <icon-ic-round-search class="text-icon" />
              </template>
              {{ $t('common.search') }}
            </NButton>
          </NSpace>
        </NFormItemGi>
      </NGrid>
    </NForm>
  </NCard>
</template>

<style scoped></style>
